<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <div class="header-title">
        <!-- 调整主标题以包含AI学习分析 -->
        <h1>AI学习分析</h1>
      </div>
      <!-- 根据需要可以添加其他头部信息 -->
    </div>

    <div class="card-container">
      <!-- 总体出勤情况统计卡片 -->
      <!-- v-loading 移到单个卡片或更小的区域，避免开始AI分析时整个页面加载 -->
      <div class="summary-card" v-loading="loadingAttendance">
        <div class="card-header">
          <h2>总体出勤情况</h2>
          <span class="update-time">更新时间：{{ formattedTime }}</span>
        </div>
        <div class="summary-content">
          <div class="chart-container" id="summary-chart"></div>
          <div class="summary-stats">
            <div class="stat-item present">
              <div class="stat-icon"><i class="el-icon-user"></i></div>
              <div class="stat-details">
                <div class="stat-value">{{ totalPresent }}<span class="percent-sign"></span></div>
                <div class="stat-label">总出勤人次</div>
              </div>
            </div>
            <div class="stat-item absent">
              <div class="stat-icon"><i class="el-icon-user-solid"></i></div>
              <div class="stat-details">
                <div class="stat-value">{{ totalAbsent }}<span class="percent-sign"></span></div>
                <div class="stat-label">总缺勤人次</div>
              </div>
            </div>
            <div class="stat-item rate">
              <div class="stat-icon"><i class="el-icon-data-analysis"></i></div>
              <div class="stat-details">
                <div class="stat-value">{{ attendanceRate }}<span class="percent-sign">%</span></div>
                <div class="stat-label">总出勤率</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 新增 AI 学情分析卡片 -->
      <div class="ai-analysis-card" v-loading="loadingAnalysis">
        <div class="card-header">
          <h2>AI学情分析</h2>
          <el-button
              type="primary"
              size="small"
          @click="startAIAnalysis"
          :disabled="loadingAnalysis"
          >
          开始分析
          </el-button>
        </div>
        <div class="analysis-results">
          <!-- 展示分析结果的区域 -->
          <template v-if="analysisResults">
            <div v-html="analysisResults"></div>
          </template>
          <template v-else-if="!loadingAnalysis">
            <div class="placeholder">
              <i class="el-icon-data-line"></i>
              <span>点击“开始分析”获取AI学情分析结果</span>
            </div>
          </template>
          <!-- 加载动画由 v-loading 指令处理 -->
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'; // 引入 ECharts
// 如果你使用的是Element UI的按钮和加载指令，请确保已全局或局部注册
// import { Button, Loading } from 'element-ui'; // 示例局部导入

export default {
  name: 'AILearningAnalysis', // 组件名称
  // components: { ElButton: Button }, // 示例局部注册Element UI按钮

  data() {
    return {
      // 总体出勤情况相关数据
      totalPresent: 0,
      totalAbsent: 0,
      attendanceRate: 0,
      lastUpdated: new Date(),
      loadingAttendance: false, // 出勤数据加载状态
      chart: null, // ECharts 实例

      // AI 学情分析相关数据
      loadingAnalysis: false, // AI分析加载状态
      analysisResults: '', // 存储AI分析结果
      // 注意：这里不包含学生排名相关的数据
    };
  },
  computed: {
    // 格式化更新时间
    formattedTime() {
      const date = new Date(this.lastUpdated);
      if (isNaN(date)) {
        return '未知时间';
      }
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }
  },
  mounted() {
    console.log('AILearningAnalysis mounted.');
    // 检查初始 loadingAnalysis 状态
    console.log('Initial loadingAnalysis:', this.loadingAnalysis);

    // 组件挂载后获取出勤数据并初始化图表
    this.fetchAttendanceData();
    // 添加窗口resize事件监听器，用于图表自适应
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    console.log('AILearningAnalysis beforeDestroy.');
    // 组件销毁前移除事件监听器并销毁图表实例
    window.removeEventListener('resize', this.resizeChart);
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    // 获取出勤数据的方法 (沿用原API)
    async fetchAttendanceData() {
      this.loadingAttendance = true; // 开始加载出勤数据
      console.log('Fetching attendance data...');
      try {
        // 使用原有的API路径 /attendance/summary
        const response = await this.$request.get('/attendance/summary');

        if (response && typeof response.presentCount !== 'undefined' && typeof response.absentCount !== 'undefined' && typeof response.attendanceRate !== 'undefined') {
          this.totalPresent = response.presentCount;
          this.totalAbsent = response.absentCount;
          // 确保 attendanceRate 是数字，并处理toFixed可能带来的问题
          this.attendanceRate = parseFloat(response.attendanceRate) || 0;
          this.lastUpdated = response.lastUpdated ? new Date(response.lastUpdated) : new Date();
          console.log('Attendance data fetched successfully.');
        } else {
          console.error("API返回出勤数据格式不正确或数据不完整", response);
          this.totalPresent = 0;
          this.totalAbsent = 0;
          this.attendanceRate = 0;
          this.lastUpdated = new Date();
        }

        // 数据获取成功后初始化图表
        this.$nextTick(() => {
          this.initChart();
        });

      } catch (error) {
        console.error("获取出勤数据失败:", error);
        this.totalPresent = 0;
        this.totalAbsent = 0;
        this.attendanceRate = 0;
        this.lastUpdated = new Date();
        if (this.chart) {
          this.chart.dispose();
          this.chart = null;
        }
      } finally {
        this.loadingAttendance = false; // 结束加载出勤数据
        console.log('Finished fetching attendance data. loadingAttendance:', this.loadingAttendance);
      }
    },

    // 初始化ECharts饼图
    initChart() {
      const chartDom = document.getElementById('summary-chart');
      if (!chartDom) {
        console.error("ECharts容器元素 '#summary-chart' 未找到!");
        return;
      }

      if (this.chart) {
        this.chart.dispose();
      }

      this.chart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 0,
          data: ['出勤', '缺勤']
        },
        color: ['#67C23A', '#F56C6C'],
        series: [
          {
            name: '出勤情况',
            type: 'pie',
            radius: ['55%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              formatter: () => {
                // 防止除以零或数据显示异常，并保留一位小数
                const rate = this.attendanceRate !== null && typeof this.attendanceRate !== 'undefined' ? this.attendanceRate.toFixed(1) : 0;
                return `出勤率\n${rate}%`;
              },
              fontSize: 16,
              fontWeight: 'bold',
              color: '#303133'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {value: this.totalPresent, name: '出勤'},
              {value: this.totalAbsent, name: '缺勤'}
            ]
          }
        ]
      };

      this.chart.setOption(option);
    },

    // 窗口大小改变时重置图表大小
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },


    async startAIAnalysis() {
      console.log('startAIAnalysis called. loadingAnalysis before setting true:', this.loadingAnalysis);
      this.loadingAnalysis = true; // 开始加载AI分析
      this.analysisResults = ''; // 清空之前的分析结果

      try {
        console.log("正在进行AI学情分析...");
        // 实际中这里会调用后端API
        // const simulatedResponse = await this.$request.post('/ai-learning/analyze', { parameters: '...' });

        // 为了演示，这里使用 setTimeout 模拟网络延迟和异步操作
        const simulatedResponse = await new Promise(resolve => {
          setTimeout(() => {
            const result = {
              overview: '基于近期出勤数据统计，各课程出勤情况差异显著，部分课程缺勤问题较为突出。',
              strengths: [
                'Spark课程出勤率高达约83.8%，缺勤人数最少（152人），到课情况优异。',
                'Kafka课程出勤率约81.8%，出勤人数最多（1082人），学生参与度高。'
              ],
              weaknesses: [
                'Flink课程出勤率仅约42.7%，缺勤人数（419人）多于出勤人数（312人）。',
                'HBase课程出勤率最低（约43.3%），缺勤人数（560人）远超出勤人数（428人）。'
              ],
              suggestions: [
                '**重点干预低出勤率课程**：对Flink和HBase开展缺勤原因调研（如课程难度、教学方法、时间冲突等）。',
                '**优化教学与管理**：与Flink/HBase授课教师沟通，改进教学方法（增加互动、案例实践），调整课程评估方式。',
                '**强化考勤机制**：将课堂表现纳入成绩考核，加强考勤纪律宣导，建立学生个体缺勤跟踪记录。',
                '**推广成功经验**：组织Spark/Kafka教师分享教学经验，开展跨课程教学方法交流会。',
                '**完善数据管理**：建立全校课程出勤数据横向/纵向分析机制，定期生成考勤预警报告。'
              ],
              conclusion: '整体出勤情况呈现两极分化，需重点解决Flink/HBase缺勤问题，同时推广高参与度课程的教学模式，通过数据驱动优化教学管理。'
            };
            resolve(result);
          }, 1340); // 模拟3秒的分析时间
        });

        console.log("AI Analysis raw response:", simulatedResponse);
        // 格式化分析结果以便在HTML中显示
        this.analysisResults = this.formatAnalysisResultHtml(simulatedResponse);
        console.log("AI Analysis results formatted.");

      } catch (error) {
        console.error("AI学情分析失败:", error);
        this.analysisResults = '<p style="color: #F56C6C;">AI学情分析过程中发生错误，请稍后再试。</p>';
      } finally {
        this.loadingAnalysis = false; // 结束加载AI分析
        console.log("AI学情分析完成. loadingAnalysis after setting false:", this.loadingAnalysis);
      }
    },

    // 辅助方法：将分析结果对象格式化为HTML字符串
    formatAnalysisResultHtml(result) {
      if (!result) return '<p>无分析结果。</p>';

      let html = '<h3>分析报告</h3>';
      if (result.overview) {
        html += `<p><strong>概览：</strong>${result.overview}</p>`;
      }
      if (result.strengths && result.strengths.length > 0) {
        html += '<p><strong>优势：</strong></p><ul>';
        result.strengths.forEach(item => {
          html += `<li>${item}</li>`;
        });
        html += '</ul>';
      }
      if (result.weaknesses && result.weaknesses.length > 0) {
        html += '<p><strong>待改进项：</strong></p><ul>';
        result.weaknesses.forEach(item => {
          html += `<li>${item}</li>`;
        });
        html += '</ul>';
      }
      if (result.suggestions && result.suggestions.length > 0) {
        html += '<p><strong>改进建议：</strong></p><ul>';
        result.suggestions.forEach(item => {
          html += `<li>${item}</li>`;
        });
        html += '</ul>';
      }
      if (result.conclusion) {
        html += `<p><strong>总结：</strong>${result.conclusion}</p>`;
      }
      return html;
    }
  }
};
</script>

<style scoped>
/* 沿用并新增样式 */

.dashboard-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #ffffff;
  min-height: calc(100vh - 84px);
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.header-title h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-container {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 卡片之间的间距 */
}

/* 总体出勤情况卡片样式 (沿用) */
.summary-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
  height: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f2f2f2;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.update-time {
  font-size: 12px;
  color: #909399;
}

.summary-content {
  display: flex;
  height: 260px;
}

.chart-container {
  height: 100%;
  flex: 1;
}

.summary-stats {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  gap: 10px;
  width: 35%;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 6px;
  color: white;
  gap: 12px;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  position: relative;
  overflow: hidden;
}

.stat-item:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0) 60%);
  pointer-events: none;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}


.stat-item.present {
  background-color: #67C23A;
}

.stat-item.absent {
  background-color: #F56C6C;
}

.stat-item.rate {
  background-color: #409EFF;
}

.stat-icon {
  font-size: 20px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  min-width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.stat-details {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  letter-spacing: 0.5px;
  line-height: 1;
  display: flex;
  align-items: baseline;
  font-family: "Arial", "PingFang SC", "Hiragino Sans GB", sans-serif;
  margin-bottom: 4px;
}

.percent-sign {
  font-size: 16px;
  font-weight: normal;
  margin-left: 2px;
}

.stat-label {
  font-size: 13px;
  opacity: 0.9;
  font-weight: 500;
}

#summary-chart {
  width: 65%;
}

/* 新增 AI 学情分析卡片样式 (沿用) */
.ai-analysis-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
  height: auto; /* 高度自适应内容 */
  min-height: 300px; /* 保证一个最小高度，使加载动画有空间 */
  position: relative; /* 为 v-loading 提供定位上下文 */
}

.analysis-results {
  /* 样式化结果展示区域 */
  padding-top: 10px; /* 与 header 分隔 */
  color: #606266;
  line-height: 1.8;
  font-size: 14px;
  max-height: 500px; /* 限制最大高度并允许滚动 */
  overflow-y: auto;
}

.analysis-results h3 {
  color: #303133;
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
}

.analysis-results p {
  margin-bottom: 10px;
}

.analysis-results ul {
  margin-top: 5px;
  margin-bottom: 10px;
  padding-left: 20px;
}

.analysis-results li {
  margin-bottom: 5px;
}

.placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%; /* 占满父容器高度 */
  min-height: 200px; /* 确保有可见区域 */
  color: #909399;
  gap: 10px;
}

.placeholder i {
  font-size: 48px;
}


/* 媒体查询调整布局 (沿用并确保新卡片也响应) */
@media (max-width: 768px) {
  .summary-card, .ai-analysis-card { /* 同时应用于两个卡片 */
    height: auto;
    min-height: auto; /* 小屏幕下移除最小高度限制 */
  }

  .summary-content {
    flex-direction: column;
    height: auto;
  }

  #summary-chart {
    width: 100%;
    height: 250px;
    margin-bottom: 20px;
  }

  .summary-stats {
    width: 100%;
  }

  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}

@media (max-width: 480px) {

}
</style>